<script setup>
import { ref } from 'vue'
import { getUserInfo, saveUserInfo } from '@/api/user'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'

// 获取登录用户信息
const userStore = useUserStore();
console.log(userStore.id);

const form = ref({
    userid: userStore.id,
    nickName: '',
    phonenumber: '',
    email: '',
    sex: ''
})

const rules = ref({
  nick_name: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  email: [{ required: true, message: "邮箱地址不能为空", trigger: "blur" }, { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
  phonenumber: [{ required: true, message: "手机号码不能为空", trigger: "blur" }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
});

// 获取用户信息
const getUserInfos = async () => {
  const res = await getUserInfo(userStore.id);
  console.log(res);
  form.value = res.rows[0];
  console.log(form.value);
};
getUserInfos();

/** 保存按钮 */
function submit() {
    saveUserInfo(form.value).then(res=>{
        if(res.code==200){
            ElMessage.success('修改成功')
        }
        getUserInfos();
  })
  .catch(err=>{
      console.log(err);
      ElMessage.error('保存失败，请重试')
  })
}

</script>

<template>
    <h2 style="padding-left: 30px;">个人资料</h2>
    <hr style="margin-bottom: 20px;">
    <div class="user-center">
        <el-form ref="userRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="用户昵称" prop="nick_name">
                <el-input v-model="form.nickName" maxlength="30" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
                <el-input v-model="form.phonenumber" maxlength="11" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" maxlength="50" />
            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="form.sex">
                    <el-radio value="0">男</el-radio>
                    <el-radio value="1">女</el-radio>
                    <el-radio value="2">保密</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item>
            <el-button type="primary" @click="submit">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<style scoped lang="scss">
.user-center{
    width: 600px;
    margin-left: 80px;
}

</style>